package Core;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import org.json.JSONObject;

import java.net.InetSocketAddress;

public class ClientInsideServer extends ChannelDuplexHandler {

    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //这里我们起了一个客户端部分，负责和登录服务器通讯，报告信息：
        //1, 本服务器的名字、host、端口，状态
        //2, 本服务器依旧在运行的回应（登录服会用心跳来检测我们的在线状态）
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class).handler(
                new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
                        String msg = in.toString(CharsetUtil.UTF_8);

                        try {
                            String response = "";

                            JSONObject json = new JSONObject(msg);
                            String id = json.getString("id");

                            switch (id) {
                                case "UploadInfoS2C":
                                    JSONObject info = new JSONObject();
                                    info.put("id", "UploadInfoC2S");

                                    String host = ConfigManager.Instance().getHost();
                                    int port = ConfigManager.Instance().getPort();
                                    String name = ConfigManager.Instance().getName();

                                    info.put("name", name);
                                    info.put("host", host);
                                    info.put("port", port);
                                    info.put("status", "Normal");

                                    response = info.toString();
                                    break;
                                case "HeartBeatReqS2C":
                                    JSONObject beat = new JSONObject();
                                    beat.put("id", "HeartBeatAckC2S");
                                    response = beat.toString();
                                    break;
                            }

                            ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
                        } catch (Exception e) {
                            Log4j2.LOGGER.error(e.toString());
                        }
                    }
                });
        EventLoopGroup clientGroup = new NioEventLoopGroup(1);
        bootstrap.group(clientGroup);

        String host = ConfigManager.Instance().getRemoteHost();
        int port = ConfigManager.Instance().getRemotePort();
        ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port));
    }
}
